package com.ibeetl.cms.web;

import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.file.FileItem;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.util.ConvertUtil;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.PlatformException;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.cms.entity.Enterprise;
import com.ibeetl.cms.entity.TelentCard;
import com.ibeetl.cms.service.EnterpriseService;
import com.ibeetl.cms.service.TelentCardService;
import com.ibeetl.cms.web.query.TelentCardQuery;
import com.ibeetl.cms.web.query2.TelentCardEnterpriseQuery;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * TelentCard 接口
 */
@Controller
public class TelentCardController{

    private final Log log = LogFactory.getLog(this.getClass());
    private static final String MODEL = "/cms/telentCard";

    @Autowired
    CorePlatformService platformService;

    @Autowired private TelentCardService telentCardService;

    @Autowired private EnterpriseService enterpriseService;
    
    @Autowired
    FileService fileService;
    /* 页面 */

    @GetMapping(MODEL + "/index.do")
    @ResponseBody
    public ModelAndView index() {
        ModelAndView view = new ModelAndView("/cms/telentCard/edit.html") ;
        view.addObject("search", TelentCardQuery.class.getName());

        CoreUser user = platformService.getCurrentUser();
        long userId = user.getId();
        TelentCardQuery condition = new TelentCardQuery();
        condition.setUserid((int) userId);
        condition.setLimit(100);
        PageQuery page = condition.getPageQuery();
        PageQuery<TelentCard> pageQuery = telentCardService.queryByCondition(page);
        List<TelentCard> telentCardList = pageQuery.getList();

        TelentCard telentCard = new TelentCard();

        view.addObject("telentCard", telentCard);
        view.addObject("talentCardList", telentCardList);

        return view;
    }

    @GetMapping(MODEL + "/edit.do")
    @Function("cms.telentCard.edit")
    @ResponseBody
    public ModelAndView edit(String id) {
        ModelAndView view = new ModelAndView("/cms/telentCard/edit.html");
        TelentCard telentCard = telentCardService.queryById(id);
        view.addObject("telentCard", telentCard);
        return view;
    }

    @GetMapping(MODEL + "/add.do")
    @Function("cms.telentCard.add")
    @ResponseBody
    public ModelAndView add() {
        ModelAndView view = new ModelAndView("/cms/telentCard/add.html");
        return view;
    }

    /* ajax json */

    @PostMapping(MODEL + "/list.json")
    @ResponseBody
    public JsonResult<PageQuery> list(TelentCardQuery condtion)
    {
        PageQuery page = condtion.getPageQuery();
        telentCardService.queryByCondition(page);
        return JsonResult.success(page);
    }

    @PostMapping(MODEL + "/add.json")
    @Function("cms.telentCard.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)TelentCard telentCard)
    {
        telentCardService.save(telentCard);
        return new JsonResult().success();
    }

    @PostMapping(MODEL + "/update.json")
    @Function("cms.telentCard.update")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  TelentCard telentCard) {
        boolean success = telentCardService.updateTemplate(telentCard);
        if (success) {
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }


   
    @GetMapping(MODEL + "/view.json")
    @Function("cms.telentCard.query")
    @ResponseBody
    public JsonResult<TelentCard>queryInfo(String id) {
        TelentCard telentCard = telentCardService.queryById( id);
        return  JsonResult.success(telentCard);
    }

    @PostMapping(MODEL + "/delete.json")
    @Function("cms.telentCard.delete")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        List<Long> idList = ConvertUtil.str2longs(ids);
        telentCardService.batchDelTelentCard(idList);
        return new JsonResult().success();
    }
    
    
    @PostMapping(MODEL + "/excel/export.json")
    @Function("cms.telentCard.export")
    @ResponseBody
    public JsonResult<String> export(HttpServletResponse response,TelentCardQuery condtion) {
        /**
         * 1)需要用你自己编写一个的excel模板
         * 2)通常excel导出需要关联更多数据，因此telentCardService.queryByCondition方法经常不符合需求，需要重写一个为模板导出的查询
         * 3)参考ConsoleDictController来实现模板导入导出
         */
        String excelTemplate ="excelTemplates/cms/telentCard/你的excel模板文件名字.xls";
        PageQuery<TelentCard> page = condtion.getPageQuery();
        //取出全部符合条件的
        page.setPageSize(Integer.MAX_VALUE);
        page.setPageNumber(1);
        page.setTotalRow(Integer.MAX_VALUE);
        //本次导出需要的数据
        List<TelentCard> list =telentCardService.queryByCondition(page).getList();
        try(InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(excelTemplate)) {
            if(is==null) {
                throw new PlatformException("模板资源不存在："+excelTemplate);
            }
            FileItem item = fileService.createFileTemp("TelentCard_"+DateUtil.now("yyyyMMddHHmmss")+".xls");
            OutputStream os = item.openOutpuStream();
            Context context = new Context();
            context.putVar("list", list);
            JxlsHelper.getInstance().processTemplate(is, os, context);
            os.close();
            //下载参考FileSystemContorller
            return  JsonResult.success(item.getPath());
        } catch (IOException e) {
            throw new PlatformException(e.getMessage());
        }
        
    }
    
    @PostMapping(MODEL + "/excel/import.do")
    @Function("cms.telentCard.import")
    @ResponseBody
    public JsonResult importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
           return JsonResult.fail();
        }
        InputStream ins = file.getInputStream();
        /*解析模板并导入到数据库里,参考DictConsoleContorller，使用jxls reader读取excel数据*/
        ins.close();
        return JsonResult.success();
    }

    /**
     ** 功能描述:所有人才卡查看
     ** @author liujun
     ** @date 2020/2/17 16:12
     **/
    @GetMapping(MODEL + "/listAll.do")
    @ResponseBody
    public ModelAndView listAll() {
        ModelAndView view = new ModelAndView("/cms/telentCard/index.html") ;
        view.addObject("search", TelentCardQuery.class.getName());

       /* TelentCardQuery condition = new TelentCardQuery();
        PageQuery page = condition.getPageQuery();
        PageQuery<TelentCard> pageQuery = telentCardService.queryByCondition(page);
        List<TelentCard> telentCardList = pageQuery.getList();

        TelentCard telentCard = new TelentCard();

        view.addObject("telentCard", telentCard);
        view.addObject("talentCardList", telentCardList);
*/
        return view;
    }

    /**
     * 企业查询人才卡
     * @param judg（1.查看历史人才卡，2.查看当前人才卡）
     * @return
     */
    @GetMapping(MODEL + "/listEnterprise.do")
    @ResponseBody
    public ModelAndView listEnterprise(String judg) {
        ModelAndView view;
        if(judg.equals("1")){
            view = new ModelAndView("/cms/telentCard/enterpriseIndex.html") ;
            view.addObject("search", TelentCardQuery.class.getName());
        }else {
            view = new ModelAndView("/cms/telentCard/nowIndex.html") ;
            view.addObject("search", TelentCardEnterpriseQuery.class.getName());
        }

        return view;
    }

    /**
     * 企业查询人才卡
     * @param judg（1.查看历史人才卡，2.查看当前人才卡）
     * @return
     */
    @PostMapping(MODEL + "/entlist.json")
    @Function("telentCard.history")
    @ResponseBody
    public JsonResult<PageQuery> entlist(String judg,TelentCardQuery condtion)
    {
        PageQuery page = condtion.getPageQuery();

        if(judg.equals("1")){
            if (condtion.getCardNumber() == null || condtion.getCardNumber() == "") {
                return JsonResult.failMessage("<font color=\"red\">证件号码</font>不能为空,请填写完整的证件号码");
            }
        }else {
            if(condtion.getSocialCreditCode()=="" || condtion.getSocialCreditCode()==null){
                CoreUser currentUser = platformService.getCurrentUser();
                Long userId = currentUser.getId();
                Enterprise enterprise= enterpriseService.queryByUserId(Integer.parseInt(userId.toString()));
                condtion.setSocialCreditCode(enterprise.getOrganizationCode());
            }

        }

        telentCardService.queryByCondition(page);
        return JsonResult.success(page);
    }

}
